<template>
  <div class="chart-container">
    <div class="chart-header">
      <h4>{{ title }}</h4>
      <div class="chart-actions">
        <el-button size="small" @click="refreshChart">刷新</el-button>
        <el-button size="small" @click="$emit('edit')">编辑</el-button>
      </div>
    </div>
    <div ref="chartRef" class="chart-content"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue'

const props = defineProps({
  title: {
    type: String,
    default: '饼图'
  },
  data: {
    type: Array,
    default: () => []
  },
  config: {
    type: Object,
    default: () => ({
      labelField: '',
      valueField: '',
      colors: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
    })
  }
})

const emit = defineEmits(['edit'])

const chartRef = ref(null)

// 简单的SVG饼图实现
const renderChart = () => {
  if (!chartRef.value || !props.data.length) return

  const container = chartRef.value
  container.innerHTML = ''

  const width = container.clientWidth || 400
  const height = container.clientHeight || 300
  const radius = Math.min(width, height) / 2 - 40
  const centerX = width / 2
  const centerY = height / 2

  // 创建SVG
  const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
  svg.setAttribute('width', width)
  svg.setAttribute('height', height)
  svg.style.background = '#fff'

  // 获取数据
  const labelField = props.config.labelField
  const valueField = props.config.valueField

  if (!labelField || !valueField) {
    const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
    text.setAttribute('x', width / 2)
    text.setAttribute('y', height / 2)
    text.setAttribute('text-anchor', 'middle')
    text.setAttribute('fill', '#909399')
    text.textContent = '请配置标签和数值字段'
    svg.appendChild(text)
    container.appendChild(svg)
    return
  }

  const data = props.data.filter(item => item[labelField] && item[valueField])
  if (!data.length) {
    const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
    text.setAttribute('x', width / 2)
    text.setAttribute('y', height / 2)
    text.setAttribute('text-anchor', 'middle')
    text.setAttribute('fill', '#909399')
    text.textContent = '暂无数据'
    svg.appendChild(text)
    container.appendChild(svg)
    return
  }

  // 计算总值和角度
  const total = data.reduce((sum, item) => sum + (Number(item[valueField]) || 0), 0)
  let currentAngle = -Math.PI / 2 // 从顶部开始

  data.forEach((item, index) => {
    const value = Number(item[valueField]) || 0
    const percentage = value / total
    const angle = percentage * 2 * Math.PI
    const endAngle = currentAngle + angle

    // 计算路径
    const x1 = centerX + radius * Math.cos(currentAngle)
    const y1 = centerY + radius * Math.sin(currentAngle)
    const x2 = centerX + radius * Math.cos(endAngle)
    const y2 = centerY + radius * Math.sin(endAngle)

    const largeArcFlag = angle > Math.PI ? 1 : 0

    const pathData = [
      `M ${centerX} ${centerY}`,
      `L ${x1} ${y1}`,
      `A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2}`,
      'Z'
    ].join(' ')

    // 创建扇形
    const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
    path.setAttribute('d', pathData)
    path.setAttribute('fill', props.config.colors[index % props.config.colors.length])
    path.setAttribute('stroke', '#fff')
    path.setAttribute('stroke-width', '2')
    path.style.cursor = 'pointer'
    
    // 添加悬停效果
    path.addEventListener('mouseenter', () => {
      path.setAttribute('opacity', '0.8')
    })
    path.addEventListener('mouseleave', () => {
      path.setAttribute('opacity', '1')
    })
    
    svg.appendChild(path)

    // 添加标签
    if (percentage > 0.05) { // 只显示占比大于5%的标签
      const labelAngle = currentAngle + angle / 2
      const labelRadius = radius * 0.7
      const labelX = centerX + labelRadius * Math.cos(labelAngle)
      const labelY = centerY + labelRadius * Math.sin(labelAngle)

      const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
      text.setAttribute('x', labelX)
      text.setAttribute('y', labelY)
      text.setAttribute('text-anchor', 'middle')
      text.setAttribute('dominant-baseline', 'middle')
      text.setAttribute('font-size', '12')
      text.setAttribute('fill', '#fff')
      text.setAttribute('font-weight', 'bold')
      text.textContent = `${(percentage * 100).toFixed(1)}%`
      svg.appendChild(text)
    }

    currentAngle = endAngle
  })

  // 添加图例
  const legendStartY = 20
  data.forEach((item, index) => {
    const legendY = legendStartY + index * 20
    
    // 图例色块
    const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect')
    rect.setAttribute('x', width - 120)
    rect.setAttribute('y', legendY - 6)
    rect.setAttribute('width', 12)
    rect.setAttribute('height', 12)
    rect.setAttribute('fill', props.config.colors[index % props.config.colors.length])
    svg.appendChild(rect)

    // 图例文字
    const text = document.createElementNS('http://www.w3.org/2000/svg', 'text')
    text.setAttribute('x', width - 100)
    text.setAttribute('y', legendY + 3)
    text.setAttribute('font-size', '12')
    text.setAttribute('fill', '#303133')
    text.textContent = `${item[labelField]} (${Number(item[valueField]).toLocaleString()})`
    svg.appendChild(text)
  })

  container.appendChild(svg)
}

const refreshChart = () => {
  nextTick(() => {
    renderChart()
  })
}

onMounted(() => {
  renderChart()
})

watch(() => [props.data, props.config], () => {
  renderChart()
}, { deep: true })
</script>

<style scoped>
.chart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.chart-header h4 {
  margin: 0;
  font-size: 14px;
  color: #303133;
}

.chart-actions {
  display: flex;
  gap: 8px;
}

.chart-content {
  flex: 1;
  min-height: 200px;
  padding: 16px;
}
</style>
